<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>作为对象属性的Generator函数</title>
</head>
<body>
    <h1>作为对象属性的Generator函数</h1>

    <script>
        // 对象的Generator函数写法
        const obj = {
            * myGenerator() {
                yield 'hello';
                yield 'world';
            }
        };

        // 等同于
        const obj2 = {
            myGenerator: function* () {
                yield 'hello';
                yield 'world';
            }
        };

        // 使用示例
        const gen = obj.myGenerator();
        console.log(gen.next()); // { value: "hello", done: false }
        console.log(gen.next()); // { value: "world", done: false }
        console.log(gen.next()); // { value: undefined, done: true }

        // 在类中使用Generator函数
        class Collection {
            constructor() {
                this.items = [];
            }

            *[Symbol.iterator]() {
                for (let item of this.items) {
                    yield item;
                }
            }

            add(item) {
                this.items.push(item);
            }

            *entries() {
                for (let i = 0; i < this.items.length; i++) {
                    yield [i, this.items[i]];
                }
            }
        }

        const collection = new Collection();
        collection.add('A');
        collection.add('B');
        collection.add('C');

        for (let [index, value] of collection.entries()) {
            console.log(index, value);
        }
    </script>
</body>
</html> 